package com.books.activity

import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import base.QActivity
import com.blankj.utilcode.util.LogUtils
import com.books.R
import com.books.adapter.BookReadAdapter
import com.books.adapter.BooksLrytAdapter
import com.books.databinding.BooksReadActivityBinding
import com.books.model.BookReadDataModel
import com.books.model.BookViewModel
import kotlinx.coroutines.launch

class BookReadActivity : QActivity() {


var viewModel : BookViewModel ? =null;
   var binding: BooksReadActivityBinding ?=null;


    var adapter : BookReadAdapter ?=null;

    var name: String? = null;
    override fun getLayoutRes(): Int {
        return R.layout.books_read_activity
    }

    override fun initView() {

    }

    override fun initData() {
         viewModel = ViewModelProvider(this).get(BookViewModel::class.java)
binding= DataBindingUtil.setContentView(this, getLayoutRes());

        name = intent.getStringExtra("name")

        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        binding!!.rvBookRead.layoutManager = layoutManager
        adapter = BookReadAdapter(R.layout.book_read_item)
        binding!!.rvBookRead.adapter = adapter






    }

    override fun initListener() {

    }

    override fun networkMessage() {
        name?.let { getBookNameSourceModel(it) }
    }

    fun getBookNameSourceModel(name: String) {

        //发起网络请求
        lifecycleScope.launch {
             viewModel!!.getBookNameSourceModel(name)
        }


        lifecycleScope.launch {
            viewModel!!.bookSource.collect {
                LogUtils.d("根据书籍名称获取不同来源站" + it.data.toString())
                getBookInfo(it.data.get(0).url)

            }
        }

    }

     fun getBookInfo(newUrl :String){
         lifecycleScope.launch {
             viewModel?.getBookInfo(newUrl)
         }


         lifecycleScope.launch {
             viewModel!!.bookInfo.collect {
                 if(it.data.list!=null){
                     LogUtils.d("获取书籍信息" + it.data.list.toString())
//              getBookReadData(it.data.list.get(0).url)
                     getBookReadData(it.data.list[0].url)

//                     adapter?.replaceData(it.data.list)
                 }


             }
         }


    }


    fun getBookReadData(newUrl: String){

        lifecycleScope.launch {
            viewModel?.getBookReadData(newUrl)
        }


        lifecycleScope.launch {
            viewModel!!.bookReadData.collect {
                LogUtils.d("获取书籍信息内容数据" + it.data)
//                adapter?.replaceData(it.data)

                adapter?.replaceData(listOf(it.data))
            }
        }
    }
}